package com.foo.demo.util;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

public class PropertiesUtil {
    private static final Logger logger = LogManager.getLogger();

    private static Map<String, Properties> cache = new HashMap<>();

    private PropertiesUtil() {
    }

    public static Properties loadProperties(String filePath) {
        Properties value = cache.get(filePath);
        if (null != value) {
            logger.info("从cache中获取数据, 文件为：" + filePath);
            return value;
        }
        InputStream resourceAsStream = PropertiesUtil.class.getClassLoader().getResourceAsStream(filePath);

        if (null == resourceAsStream) {
            throw new RuntimeException(filePath + "文件不存在");
        }

        try {
            Properties properties = new Properties();
            properties.load(new InputStreamReader(resourceAsStream));
            cache.put(filePath, properties);
            return properties;
        } catch (Exception e) {
            logger.error(e);
            return null;
        }
    }

    public static String getValue(String filePath, String key) {
        Properties properties = loadProperties(filePath);
        if (null == properties) {
            return null;
        }
        return properties.getProperty(key);
    }

}
